package com.lisn.recyclerviewlib;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import static android.provider.MediaStore.Video.Thumbnails.MINI_KIND;

/**
 * Android之exif格式 ExifInterface
 * https://www.jianshu.com/p/18eaa4f8c58a
 */


public class ImgVideoInfoActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = ImgVideoInfoActivity.class.getSimpleName();
    String filename = "/storage/emulated/0/Android/data/com.nari.portablemobileterminal/files/20200713-185250.mp4";
//    String filename = "/storage/emulated/0/Android/data/com.nari.portablemobileterminal/files/20200713-184643.mp4";
    //    String filename = "/storage/emulated/0/Android/data/com.nari.portablemobileterminal/files/20200713103002.jpg";
//    String filename = "/sdcard/DCIM/Camera/IMG_20200713_104601.jpg";
    EditText et_key, et_valuer;
    Button bt_get, bt_set;
    private Button bt_AddVideoToDcim;
    private Button bt_getVideoThumbnail;
    private ImageView iv;


    private static final String[] PERMISSIONS = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO};
    private static final int PERMISSION_CODE = 1000;
    private ArrayList<String> deniedPermission = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_img_video_info);
        et_key = findViewById(R.id.et_key);
        et_valuer = findViewById(R.id.et_valuer);
        bt_get = findViewById(R.id.bt_get);
        bt_set = findViewById(R.id.bt_set);
        bt_AddVideoToDcim = findViewById(R.id.bt_AddVideoToDcim);
        bt_getVideoThumbnail = findViewById(R.id.bt_getVideoThumbnail);
        iv = findViewById(R.id.iv);

        bt_get.setOnClickListener(this);
        bt_set.setOnClickListener(this);
        bt_AddVideoToDcim.setOnClickListener(this);
        bt_getVideoThumbnail.setOnClickListener(this);

        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_CODE);
    }

    public static void startActivity(Context context) {
        context.startActivity(new Intent(context, ImgVideoInfoActivity.class));
    }

    public void get(String key) {
        try {
            ExifInterface exifInterface = new ExifInterface(filename);//文件全路径名
            String TAG_valuer = exifInterface.getAttribute(key);
            Log.e(TAG, "get: valuer = " + TAG_valuer);
            Toast.makeText(this, "valuer = " + TAG_valuer, Toast.LENGTH_SHORT).show();
            if (exifInterface.hasThumbnail()) {
                Log.e(TAG, "get: hasThumbnail");

            } else {
//                byte[] thumbnail = exifInterface.getThumbnail();
//                Log.e(TAG, "get: " + Arrays.toString(thumbnail));
            }

            Uri uri = Uri.parse(filename);
            File file = new File(filename);
            uri = Uri.fromFile(file);
            String thumbnailPath = getThumbnailPathForLocalFile(ImgVideoInfoActivity.this, uri);
            Log.e(TAG, "get: thumbnailPath=" + thumbnailPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void set(String key, String valuer) {
        try {
            ExifInterface exif = new ExifInterface(filename);
            // 保存指定tag的值
            //exif.setAttribute(key, valuer);
            exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, valuer);
            // 把Exif信息写入目标图片
            exif.saveAttributes();

            Log.e(TAG, "set: 写入成功");
        } catch (IOException e) {
            Log.e(TAG, "set: 写入失败" + e);
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        if (v == bt_get) {
            get(et_key.getText().toString().trim());
        } else if (v == bt_set) {
            set(et_key.getText().toString().trim(), et_valuer.getText().toString().trim());
        } else if (v == bt_AddVideoToDcim) {
            AddVideoToDcim(new File(filename));
        } else if (v == bt_getVideoThumbnail) {
            try {

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String[] thumbColumns = {MediaStore.Video.Thumbnails.DATA};
    public static String[] mediaColumns = {MediaStore.Video.Media._ID};

    public static String getThumbnailPathForLocalFile(Activity context, Uri fileUri) {

        long fileId = getFileId(context, fileUri);
        MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(),
                fileId, MediaStore.Video.Thumbnails.MICRO_KIND, null);
        Cursor thumbCursor = null;
        try {
            thumbCursor = context.managedQuery(
                    MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
                    thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID + " = "
                            + fileId, null, null);

            if (thumbCursor.moveToFirst()) {
                String thumbPath = thumbCursor.getString(thumbCursor
                        .getColumnIndex(MediaStore.Video.Thumbnails.DATA));
                Log.e(TAG, "getThumbnailPathForLocalFile: thumbPath=" + thumbPath);
                return thumbPath;
            }

        } finally {
        }

        return null;
    }

    public static long getFileId(Activity context, Uri fileUri) {

        Cursor cursor = context.managedQuery(fileUri, mediaColumns,
                null, null, null);
        Log.e(TAG, "getFileId: cursor != null =" + (cursor != null));
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
            int id = cursor.getInt(columnIndex);
            return id;
        }
        return 0;
    }

    public static String getVideoThumbnailPath(Context context, String filePath) {
        String thubmnailPath;
        String where = MediaStore.Video.Thumbnails.VIDEO_ID
                + " In ( select _id from video where _data =?)";
        final String[] VIDEO_THUMBNAIL_TABLE = new String[]{MediaStore.Video.Media._ID, // 0
                MediaStore.Video.Media.DATA, // 1
        };
        Uri videoUri = MediaStore.Video.Thumbnails.getContentUri("external");

        Cursor c = context.getContentResolver().query(videoUri,
                VIDEO_THUMBNAIL_TABLE, where, new String[]{filePath}, null);

        if ((c != null) && c.moveToFirst()) {
            thubmnailPath = c.getString(1);
            c.close();
            Log.i(TAG, "thumb path: " + thubmnailPath);
            return thubmnailPath;
        } else {
            c.close();
            Log.i(TAG, "thumb path is null");
            return null;
        }
    }

    //添加视频文件到相册
    public void AddVideoToDcim(File file) {
        ContentResolver localContentResolver = this.getContentResolver();
        ContentValues localContentValues = getVideoContentValues(this, file, System.currentTimeMillis());
        Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri));
    }

    public static ContentValues getVideoContentValues(Context paramContext, File paramFile, long paramLong) {
        ContentValues localContentValues = new ContentValues();
        localContentValues.put("title", paramFile.getName());
        localContentValues.put("_display_name", paramFile.getName());
        localContentValues.put("mime_type", "video/mp4");
        localContentValues.put("datetaken", Long.valueOf(paramLong));
        localContentValues.put("date_modified", Long.valueOf(paramLong));
        localContentValues.put("date_added", Long.valueOf(paramLong));
        localContentValues.put("_data", paramFile.getAbsolutePath());
        localContentValues.put("_size", Long.valueOf(paramFile.length()));
        return localContentValues;
    }

    /**
     * 获取视频的缩略图
     * 先通过ThumbnailUtils来创建一个视频的缩略图，然后再利用ThumbnailUtils来生成指定大小的缩略图。
     * 如果想要的缩略图的宽和高都小于MICRO_KIND，则类型要使用MICRO_KIND作为kind的值，这样会节省内存。
     *
     * @param videoPath 视频的路径
     * @param width     指定输出视频缩略图的宽度
     * @param height    指定输出视频缩略图的高度度
     * @param kind      参照MediaStore.Images.Thumbnails类中的常量MINI_KIND和MICRO_KIND。
     *                  其中，MINI_KIND: 512 x 384，MICRO_KIND: 96 x 96
     * @return 指定大小的视频缩略图
     */
    private Bitmap getVideoThumbnail(String videoPath, int width, int height,
                                     int kind) {
        Bitmap bitmap = null;
        // 获取视频的缩略图
        bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
        System.out.println("w" + bitmap.getWidth());
        System.out.println("h" + bitmap.getHeight());
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_CODE) {
            deniedPermission.clear();
            for (int i = 0; i < permissions.length; i++) {
                String permission = permissions[i];
                int result = grantResults[i];
                if (result != PackageManager.PERMISSION_GRANTED) {
                    deniedPermission.add(permission);
                }
            }

            if (deniedPermission.isEmpty()) {
                Log.e(TAG, "onRequestPermissionsResult: ok");
            } else {
                new AlertDialog.Builder(this)
                        .setMessage("必须的权限没有得到授权，功能将无法使用 请重新授权!")
                        .setNegativeButton("不", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                ImgVideoInfoActivity.this.finish();
                            }
                        })
                        .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String[] denied = new String[deniedPermission.size()];
                                ActivityCompat.requestPermissions(ImgVideoInfoActivity.this, deniedPermission.toArray(denied), PERMISSION_CODE);
                            }
                        }).create().show();
            }
        }
    }

}